// import UAParser from 'ua-parser-js';
// import moment from 'moment';

import KNB from '@dp/knb';

import {
    PASS_VERIFY_HOST,
    MERCHANT_NO,
    PARTNER_ID
} from './constants';

const toString = Object.prototype.toString;

export function isArray (obj) {
  return toString.call(obj) === '[object Array]';
}

export function isObject (obj) {
  return toString.call(obj) === '[object Object]';
}
/**
 * @param  {} obj 需要遍历的对象，数组[]or对象{}
 * @param  {} cb  遍历obj的回调函数
 */
export function each (obj, cb) {
  if (isArray(obj)) {
    obj.forEach(cb);
  } else if (isObject(obj)) {
    Object.keys(obj).forEach((key, val) => {
      cb(obj[key], key, obj);
    });
  }
}
/**
 * @param  {} obj 需要map的的对象，数组[]or对象{}
 * @param  {} cb  map obj的回调函数
 */
export function map (obj, cb) {
  let result = [];
  if (isArray(obj)) {
    result = obj.map(cb);
  } else if (isObject(obj)) {
    Object.keys(obj).forEach((key, val) => {
      result.push(cb(obj[key], key, obj));
    });
  }
  return result;
}

/**
 * 获取当前环境
 * @returns dev | test | st | prod
 */
export const env = (function () {
  let env = 'prod';
  if (location.hostname === 'localhost') {
    env = 'dev';
  } else if (location.hostname.indexOf('expenses.fin.test.meituan.com') > -1) { // expenses.fin.test.meituan.co
    env = getParamFromSearch('env');
    if (env !== 'dev' && env !== 'st') {
      env = 'test';
    }
  }
  return env;
})();

export function passVerify (successUrl, newWindow = true) {
  let url = `${PASS_VERIFY_HOST[env]}?merchantNo=${MERCHANT_NO}&partnerId=${PARTNER_ID}&successUrl=${encodeURIComponent(successUrl)}`;

  if (newWindow) {
    KNB.openWebview({
      url: url
    });
  } else {
    location.href = url;
  }
}

/**
 * @description 获取search中的查询参数
 * @param  {string} key
 * @return {string} value
 * @example
 *      http://i.meituan.com/awp/app/app-cashloan/index.html?userid=123456
 *      userid => 123456
 */
export function getParamFromSearch (key) {
  const params = {};
  if (location.search) {
    location.search.substring(1).split('&').forEach((it) => {
      let arr = it.split('=');
      params[arr[0]] = arr[1];
    });
  }
  return decodeURIComponent(params[key] || '');
}

/**
 * @description 获取hash中的查询参数
 * @param  {string} key
 * @return {string} value
 * @example
 *      http://i.meituan.com/awp/app/app-cashloan/index.html/faq/detail?id=100001
 *      id => 100001
 */
export function getParamFromHash (key) {
  const params = {};
  if (location.hash) {
    location.hash.replace(/.*\?/, '').split('&').forEach((it) => {
      let arr = it.split('=');
      params[arr[0]] = arr[1];
    });
  }
  return decodeURIComponent(params[key] || '');
}

export function getRedirectUrl (target, paramObj) {
  const prefix = location.protocol + '//' +
        location.hostname +
        location.pathname + '/';
  const search = location.hash.replace(/.*\?/, '');
  let url = location.href;

  if (typeof target === 'string') {
    url = prefix + target + '?' + search;
    if (paramObj) {
        /* eslint-disable */
        for (let key in paramObj) {
            url += '&' + key + '=' + paramObj[key];
        }
        /* eslint-disable */
    }
  }

  return url;
}

export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result;

    const getTime = (Date.now || function() {
        return new Date().getTime();
    });

    const later = function() {
        var last = getTime() - timestamp;

        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last);
        } else {
            timeout = null;
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            }
        }
    };

    return function() {
        context = this;
        args = arguments;
        timestamp = getTime();
        const callNow = immediate && !timeout;
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }

        return result;
    };
};

/**
 * @param  {(number|string)} n
 * @returns {string} result 格式化后的数据
 */
export function formatePrice(n) {
    let num = typeof n === 'string' ? n : (n || 0).toString();
    let result = '', numArr = num.split('.');
    while (numArr[0].length > 3) {
        result = ',' + numArr[0].slice(-3) + result;
        numArr[0] = numArr[0].slice(0, numArr[0].length - 3);
    }
    if (numArr[0]) { result = numArr[0] + result; }
    return numArr[1] ? result + '.' + numArr[1] : result;
}

/**
 * @returns {object}  风控信息的object
 *  手机制造商 : vendor
 *  手机型号 : model
 *  操作系统 : os
 *  操作系统版本 : osVersion,
 *  分辨率: resolution
 */
// export function getRiskControlInfo () {
//     let uaObj = UAParser(navigator.userAgent);
//     return {
//         vendor: uaObj.device.vendor,
//         model: uaObj.device.model,
//         os: uaObj.os.name,
//         osVersion: uaObj.os.version,
//         resolution: document.documentElement.clientWidth + 'x' + document.documentElement.clientHeight
//     }
// }
/**
 * @param  {(string|date)} date 待格式化的日期
 * @param  {string} format moment的格式化格式
 * @returns {string} 格式化后的内容
 */
// export function formatDate(date, format = 'YYYY年MM月DD日') {
//     return moment(date).format(format);
// }
/**
 * @param  {string} name 需要读取的queryString的key
 */
export function getQueryStringByName(name) {
    let result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return decodeURIComponent(result[1]);
}

export function replaceQueryStringByName(name, val) {
    let result = location.search.replace(new RegExp("[\?\&]" + name + "=([^\&]+)", "gi"), val);
    return result;
}

export function objectToQuery(obj) {
    return Object.keys(obj).map(key => {
            return key + '=' + encodeURIComponent(obj[key] === void 0 ? '' : obj[key]);
        }
    ).join('&');
}

/**
 *  meituan: 0,
    dianping: 11,
    qianbao: 23,
    maoyan: 1,
    maoyanpro: 29,
    waimai: 4,
 */
export function getAppCode (appName) {
    let code = appName;
    if (appName === 'meituan') {
        code = 0;
    } else if (appName === 'dianping') {
        code = 11;
    } else if (appName.match('waimai')) {
        code = 4;
    } else if (appName.match('imovie') || appName.match('maoyan')) {
        code = 1;
    }
    return code;
}
